import { defineComponent, ref, watch } from 'vue';
import styles from "./Filter.module.less";
import _ from 'lodash';
export default defineComponent({
  name: 'Filter',
  props: {
    columns: {
      type: Array,
      default: () => [],
    },
  },
  emits: ['change'],
  setup(props: any, { emit, expose }) {
    const updateTree = (e: any[]) => {
      return e.map(x => {
        x.key = x.dataIndex;
        x.children && x.children.length > 0 && (x.children = updateTree(x.children));
        return x;
      })
    }
    function preTree(list: any[], result: any[] = []) {
      list.forEach((node: any) => {
        if (node.children) {
          result.push(node);
          preTree(node.children, result)
        } else {
          result.push(node);
        }
      })
      return result;
    }
    const columns = ref(_.cloneDeep(props.columns));
    columns.value = updateTree(columns.value);
    const checkedKeys = ref([] as any[]);
    const checkedKeys_total = ref([] as any[]);
    checkedKeys.value = preTree(columns.value).map(x => x.dataIndex);
    checkedKeys_total.value = preTree(columns.value).map(x => x.dataIndex);
    watch(() => checkedKeys_total.value, (nv) => {
      emit('change', nv);
    }, {
      immediate: false,
      deep: true,
    })
    // 单条change
    const checkSimpleChange = (k: string, b: boolean) => {
      //原本包含，并要隐藏
      if (checkedKeys_total.value.includes(k) && !b) {
        checkedKeys.value.splice(checkedKeys.value.findIndex(x => x === k), 1);
        checkedKeys_total.value.splice(checkedKeys_total.value.findIndex(x => x === k), 1);
      }
      //原本不包含, 并要显示
      if (!checkedKeys_total.value.includes(k) && b) {
        checkedKeys.value.push(k);
        checkedKeys_total.value.push(k);
      }
    }
    const checkChange = (s: any, e: any) => {
      checkedKeys.value = s;
      checkedKeys_total.value = s.concat(e.halfCheckedKeys);
    }
    const Filter = () => (
      <div class={styles.filter} onClick={(e) => { e.stopPropagation() }}>
        <a-tree
          class={styles.tree}
          checkedKeys={checkedKeys.value}
          onCheck={(s: any, e: any) => { checkChange(s, e) }}
          checkable
          selectable={false}
          tree-data={columns.value}
        ></a-tree>
      </div>
    )
    return {
      checkSimpleChange,
      Filter,
    }
  },
  render() {
    return <this.Filter></this.Filter>
  }
})